package com.cloudcross.ssp.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.adinall.dsp.core.utils.CheckUtils;
import com.adinall.dsp.core.utils.StringUtils;
import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.consts.IndexDate;
import com.cloudcross.ssp.common.utils.DateUtil;
import com.cloudcross.ssp.model.IndexMoney;
import com.cloudcross.ssp.model.IndexTotal;
import com.cloudcross.ssp.model.RptAdxMediaStat;
import com.cloudcross.ssp.service.IndexService;
import com.cloudcross.ssp.service.form.IndexForm;

/**
 * 首页用Service
 * 
 * @author 高万超
 * @version V1.0.0 $ 2017年6月21日 下午12:23:39
 */
@Service
public class IndexServiceImpl implements IndexService {

    private Logger logger = LogManager.getLogger(getClass());

    public static final String MAPPER_RPT_ADX_MEDIA = "rptAdxMediaSqlMapper";
    public static final String MAPPER_RPT = "rptSqlMapper";
    public static final String MAPPER_ADV_BALANCE = "advBalanceSqlMapper";

    @Autowired
    private GenericIBatisDao mapper;

    public List<Map<String, Object>> stat(IndexForm form) {

        IndexDate indexDate = IndexDate.search(form.getDateIdx());

        Calendar c = Calendar.getInstance();

        form.setEndDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, c.getTime()));

        c.add(Calendar.DAY_OF_YEAR, -indexDate.day);
        form.setStartDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, c.getTime()));

        int idx = 0;
        while (idx < 10) {
            if (idx++ > 10) {
                return new ArrayList<>();
            }

            List<Map<String, Object>> result = mapper.getList(MAPPER_RPT_ADX_MEDIA + ".stat", form);

            if (!CheckUtils.isEmpty(result)) {

                return handle(result);
            }

            Date d = DateUtil.parse(form.getStartDate(), DateUtil.DateFmts.YYYY_MM_DD);
            Calendar cc = Calendar.getInstance();
            cc.setTime(d);
            cc.add(Calendar.DAY_OF_YEAR, -1);

            form.setStartDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, cc.getTime()));

            logger.info("执行了" + idx + "次");
        }

        return new ArrayList<>();
    }

    private List<Map<String, Object>> handle(List<Map<String, Object>> data) {

        List<Map<String, Object>> result = new ArrayList<>();

        for (Map<String, Object> map : data) {

            Map<String, Object> tmp = get(result, map.get("ADX"));

            if (StringUtils.toString(map.get("SOURCE")).equals("PC")) {
                tmp.put("PC", map.get("REQUEST"));
            } else {
                tmp.put("MOBILE", map.get("REQUEST"));
            }
        }

        return result;
    }

    private Map<String, Object> get(List<Map<String, Object>> result, Object val) {

        for (Map<String, Object> map : result) {

            if (map.get("ADX").equals(val)) {
                return map;
            }
        }

        Map<String, Object> map = new HashMap<>();
        map.put("ADX", val);
        result.add(map);

        return map;
    }

    public List<RptAdxMediaStat> list(IndexForm form) {

        IndexDate indexDate = IndexDate.search(form.getDateIdx());

        Calendar c = Calendar.getInstance();

        form.setEndDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, c.getTime()));

        c.add(Calendar.DAY_OF_YEAR, -indexDate.day);
        form.setStartDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, c.getTime()));

        // 首页不需要了，暂时屏蔽，以后删除 ----20170802高万超
        // // 默认聚告
        // if (form.getAdxId() == null || form.getAdxId() == 0) {
        // form.setAdxId(99);
        // }

        int idx = 0;
        while (idx < 10) {

            if (idx++ > 10) {
                return new ArrayList<>();
            }

            int count = mapper.listCount(MAPPER_RPT_ADX_MEDIA + ".listCount", form);

            if (count > 0) {
                break;
            }

            Date d = DateUtil.parse(form.getStartDate(), DateUtil.DateFmts.YYYY_MM_DD);
            Calendar cc = Calendar.getInstance();
            cc.setTime(d);
            cc.add(Calendar.DAY_OF_YEAR, -1);

            form.setStartDate(DateUtil.getDate(DateUtil.DateFmts.YYYY_MM_DD, cc.getTime()));
        }

        logger.info("执行了" + idx + "次");

        return mapper.getList(MAPPER_RPT_ADX_MEDIA + ".top", form);
    }

    public IndexTotal total(long advertiserId, long agentId) {

        Map<String, Long> params = new HashMap<>();
        params.put("advertiserId", advertiserId);
        params.put("agentId", agentId);
        return mapper.get(MAPPER_RPT + ".stat", params);
    }

    public IndexMoney money(long advertiserId, long agentId) {
        Map<String, Long> params = new HashMap<>();
        params.put("advertiserId", advertiserId);
        params.put("agentId", agentId);
        return mapper.get(MAPPER_ADV_BALANCE + ".money", params);
    }
}